<script setup lang="ts">
import { useDebounceFn } from '@vueuse/core'
import ClassStatus from './components/ClassStatus.vue'
import { ClassInfoApi } from '@/apis'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import { useDictFilterOptions, useTable } from '@/hooks'

const props = withDefaults(defineProps<Props>(), {
  studentId: undefined,
})

const emit = defineEmits(['select'])

interface Props {
  studentId?: string
  subject?: string
  classYear?: number
  classCategory?: number
  term?: string
}

const visible = ref(false)
const selectedKeys = ref<string[]>([])
const selectedRecord = ref([])

const form = reactive<ClassInfoApi.ClassQuery>({
  keyword: undefined,
  subject: 'math-xx',
  classYear: new Date().getFullYear(),
  classCategory: undefined,
  campusId: undefined,
  classroomId: undefined,
  term: undefined,
  grade: undefined,
  classTypeId: undefined,
  leadTeacherId: undefined,
  classStatus: undefined,
  saleStatus: 1,
})

// 筛选有权限的班级
// const studentId = ref()
const filterWithPermission = ref<boolean>(false)
// 更多筛选
const filterCollapsed = ref<boolean>(true)

const {
  tableData: dataList,
  loading,
  pagination,
  search,
} = useTable((page) => {
  if (props.studentId && filterWithPermission.value) {
    return ClassInfoApi.getClassWithPermissionPage({ ...form, ...page, studentId: props.studentId })
  } else {
    return ClassInfoApi.getClassPage({ ...form, ...page })
  }
}, { immediate: false })

const columns: TableInstanceColumns[] = [
  {
    title: '班级',
    slotName: 'name',
    fixed: 'left',
    width: 350,
  },
  { title: '年份科目', dataIndex: 'classYear', slotName: 'classYear', width: 150 },
  { title: '校区教室', dataIndex: 'classroomId', slotName: 'classroom', minWidth: 150, ellipsis: true, tooltip: true },
  { title: '招生进度', dataIndex: 'enrollProgress', slotName: 'enrollProgress', width: 200 },
  { title: '上课进度', dataIndex: 'totalLessonCount', slotName: 'classProgress', width: 240 },
  { title: '班级状态', dataIndex: 'classStatus', slotName: 'classStatus', minWidth: 120, filterable: {
    filters: useDictFilterOptions('ClassStatusEnum'),
    multiple: true,
  } },
  { title: '总价', dataIndex: 'totalPrice', slotName: 'totalPrice', minWidth: 120 },
]

const rowSelection = {
  type: 'radio',
  showCheckedAll: false,
  onlyCurrent: false,
}

const open = () => {
  // studentId.value = stuId
  if (props.classCategory) {
    form.classCategory = props.classCategory
  }
  if (props.term) {
    form.term = props.term
  }
  if (props.classYear) {
    form.classYear = props.classYear
  }
  if (props.subject) {
    form.subject = props.subject
  }
  visible.value = true
  selectedKeys.value = []
  search()
}

const onConfirm = async () => {
  if (selectedKeys.value.length > 0) {
    emit('select', selectedKeys.value[0], selectedRecord.value)
  }
}

const onSelect = (rowKeys, rowKey, record) => {
  // console.log(rowKeys, rowKey, record)
  selectedRecord.value = record
}

const onRowClick = (row) => {
  selectedKeys.value = [row.id]
  selectedRecord.value = row
  filterWithPermission.value = false
}

const debouncedSearch = useDebounceFn(() => {
  search()
}, 100)

watch(() => form, (_) => {
  debouncedSearch()
}, { deep: true })

watch(filterWithPermission, () => {
  search()
})

defineExpose({ open })
</script>

<template>
  <a-modal
    v-model:visible="visible"
    title="选择班级"
    width="90%"
    :ok-button-props="{ disabled: selectedKeys.length === 0 }"
    @before-ok="onConfirm"
  >
    <a-spin :loading="loading" tip="数据获取中..." class="h-full w-full">
      <ProTable
        v-model:selected-keys="selectedKeys"
        :data="dataList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        :disabled-tools="['size', 'setting']"
        :disabled-column-keys="['name']"
        @refresh="search"
        @select="onSelect"
        @row-click="onRowClick"
      >
        <template #search-panel>
          <a-space direction="vertical" size="medium">
            <a-space>
              <label class="label">关键词</label>
              <a-input-search
                v-model="form.keyword"
                class="!min-w-360px"
                placeholder="班级名称关键词"
                search-button
                allow-clear
                @press-enter="search"
              />
              <a-checkbox v-if="studentId" v-model="filterWithPermission">
                仅查看有权限的班级
              </a-checkbox>
              <!-- <DictSelect v-model="form.saleStatus" type="switch" code="SaleStatusEnum" /> -->
              <a-switch v-model="form.saleStatus" checked-value="0" unchecked-value="1" size="small" />
              <span>是否展示下架班级</span>
              <CollapseButton v-model="filterCollapsed" />
            </a-space>
            <a-space v-show="filterCollapsed" direction="vertical" size="medium">
              <a-space>
                <label class="label">学期年级</label>
                <YearTermCascader v-model:class-year="form.classYear" v-model:term="form.term" class="!min-w-200px" check-strictly />
                <DictSelect v-model="form.grade" type="select" code="Grade" placeholder="年级" class="!w-120px" />
                <DictSelect v-model="form.subject" type="select" code="Subject" placeholder="科目" class="!w-120px" />
              </a-space>

              <a-space>
                <label class="label">其他条件</label>
                <DictSelect v-model="form.classCategory" type="button" code="ClassCategoryEnum" placeholder="类型" />
                <EmployeeSelect v-model="form.leadTeacherId" type="LEAD_TEACHER" placeholder="主讲老师" class="!min-w-150px" />
                <ClassTypeSelect v-model="form.classTypeId" placeholder="班型" class="!min-w-150px" />
                <ClassroomSelect v-model="form.classroomId" placeholder="教室" class="!min-w-200px" />
              </a-space>
            </a-space>
          </a-space>
        </template>
        <template #name="{ record }">
          <CellClassInfo :id="record.id" :is-link="false" :name="record.name" :lead-teacher-name="record.leadTeacherName" :assist-teacher-name="record.assistTeacherName" />
        </template>
        <template #classYear="{ record }">
          <DictLabel v-model="record.grade" code="Grade" /> · <DictLabel v-model="record.subject" code="Subject" />
          <div class="text-13px text-gray-4">
            {{ record.classYear }}年 · <DictLabel v-model="record.term" code="TermEnum" />
          </div>
        </template>
        <template #classroom="{ record }">
          <div>{{ record.classroomName || '-' }}</div>
          <div class="text-13px text-gray-4">
            {{ record.campusName }}
          </div>
        </template>
        <template #enrollProgress="{ record }">
          <div>
            <a-progress :percent="record.planStudentCount === 0 ? 0 : record.enrollStudentCount / record.planStudentCount " :show-text="true" :steps="record.planStudentCount" size="small">
              <template #text>
                {{ record.enrollStudentCount || 0 }}/{{ record.planStudentCount || 0 }}
              </template>
            </a-progress>
            <div class="mt-1 flex flex-justify-between font-size-[13px]">
              <a-tag v-if="record.pendingPayCount" size="small" color="red">
                {{ record.pendingPayCount }}人未支付
              </a-tag>
            </div>
          </div>
        </template>
        <template #totalPrice="{ record }">
          <span class="text-orange">￥{{ record.totalPrice || 0 }}</span>
        </template>
        <template #classProgress="{ record }">
          <div>
            <a-progress :percent="!record.totalLessonCount ? 0 : record.completedLessonCount / record.totalLessonCount " :stroke-width="6">
              <template #text>
                {{ record.completedLessonCount || 0 }}/{{ record.totalLessonCount || 0 }}
              </template>
            </a-progress>
            <span class="mt-1 text-13px text-gray-4">{{ record.arrangeTemplate.startDate }} ~ {{ record.arrangeTemplate.endDate }}</span>
          </div>
        </template>
        <template #classStatus="{ record }">
          <ClassStatus code="ClassStatusEnum" :status="record.classStatus" />
        </template>
        <template #action="{ record }">
          <a-button v-permission="['edu:class:read']" type="text" @click.stop="">
            <span style="margin-right: 10px">选择</span>
            <icon-down />
          </a-button>
        </template>
      </ProTable>
    </a-spin>
  </a-modal>
</template>

<style lang="less" scoped>

</style>
